
package com.jf.cloud.service.sysmanager.remote.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.constant.PubgConstant;
import com.jf.cloud.service.sysmanager.dao.*;
import com.jf.cloud.service.sysmanager.entity.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jf.cloud.service.sysmanager.common.base.OPaging;
import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.constant.UserConstant;
import com.jf.cloud.service.sysmanager.handler.TokenHandler;
import com.jf.cloud.service.sysmanager.support.entity.Result;
import com.jf.cloud.service.sysmanager.support.web.BaseController;

/**
 * 商场物品兑换订单控制器
 * 
 * @author 代码机1.0 创建时间：2018-03-31
 */
@Controller
@RequestMapping("/appExchangeOrder")
public class AppPubgExchangeOrderController extends BaseController {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(AppPubgExchangeOrderController.class);

	/**
	 * 商场物品服务
	 */
	@Resource
	private IPubgExchangeGoodsService pubgExchangeGoodsService;

	/**
	 * 商场物品兑换订单服务
	 */
	@Resource
	private IPubgExchangeOrderService pubgExchangeOrderService;
	
	/**
	 * 员工服务
	 */
	@Resource
	private IPubgUserService pubgUserService;
	
	@Resource
	private IPubgTeamService pubgTeamService;
	
	/**
	 * 俱乐部服务
	 */
	@Resource
	private IPubgClubService pubgClubService;

    @Resource
    private IPubgUserTeamService pubgUserTeamService;

	@Resource
	private IPubgUserClubService pubgUserClubService;

	/**
	 * 资金流水服务
	 */
	@Resource
	private IPubgFinanceFlowDetailService pubgFinanceFlowDetailService;

	@Resource
	private TokenHandler tokenHandler;

	/**
	 * 获取兑换商品处理列表
	 * 
	 * @author 朱建文 创建时间：2018年4月11日 下午2:21:22
	 */
	@ResponseBody
	@RequestMapping("/getOrderDisposeList")
	public Result<List<Map<String, Object>>> getExchangeOrderClList(HttpServletRequest request, OPaging<Map<String, Object>> page) {
		Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
		result.setCode(-1);
		result.setMessage("获取兑换称号处理列表失败！");
		
		try {
			String token = getParamValueString(request, "token");
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
				return result;
			}

			// 每页数据条数
			int limit = getParamValueInteger(request, "limit", 50);
			page.setLimit(limit);

			// 第几页
			int offset = getParamValueInteger(request, "offset", -1);
			if (offset > 0) {
				page.setOffset((offset-1)*limit);
			}

			// 排序方式
			String order = getParamValueString(request, "order");
			if (StringUtil.isNotEmpty(order)) {
				page.setOrder(order);
			} else {
				page.setOrder(" DESC ");
			}
			
			// 排序字段
			String sort = getParamValueString(request, "sort");
			if (StringUtil.isNotEmpty(sort)) {
				page.setSort(sort);
			} else {
				page.setSort(" applyTime ");
			}
			
			// 获取
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(userId));
			if (pubgUser == null) {
				result.setMessage("该队员不存在");
				return result;
			}

			// 兑换状态
			String state = getParamValueString(request, "state");
			if (state == null || state.length() == 0) {
				state = "10";
			}

			if (UserConstant.USER_ROLE_10.getId().toString().equals(pubgUser.getUserRole().toString())) {
				page.getWm().put("USER_ID", userId);
			} else if (UserConstant.USER_ROLE_20.getId().toString().equals(pubgUser.getUserRole().toString())) {
				Query query = new Query();
				query.put("_LIKE$CAPTAIN_ID", "," + userId + ",");
				PubgTeam pubgTeam = pubgTeamService.find(query);
				page.getWm().put("TEAM_ID", pubgTeam.getRowId());
				page.getWm().put("USER_ROLE", UserConstant.USER_ROLE_10.getId());
				if(state.equals("10")){
					page.getWm().put("CONVERSION_STATE", state);
				}else if(state.equals("40")){
					page.getWm().put("_IN$CONVERSION_STATE","'20','30'");
				}
			} else if (UserConstant.USER_ROLE_30.getId().toString().equals(pubgUser.getUserRole().toString())) {
				Query query = new Query();
				query.put("_LIKE$MINISTER_ID", "," + userId + ",");
				PubgClub pubgClub = pubgClubService.find(query);
				page.getWm().put("CLUB_ID", pubgClub.getRowId());
				page.getWm().put("USER_ROLE", UserConstant.USER_ROLE_20.getId());
				if(state.equals("10")){
					page.getWm().put("CONVERSION_STATE", state);
				}else if(state.equals("40")){
					page.getWm().put("_IN$CONVERSION_STATE","'20','30'");
				}
			} else {
				page.getWm().put("USER_ID", userId);
			}
			
			List<Map<String, Object>> dataList = this.pubgExchangeOrderService.getExchageOrderList(page);
			result.setCode(0);
			result.setData(dataList);
			result.setMessage("获取兑换称号处理列表成功！");
		} catch (Exception e) {
			log.error("前台获取兑换称号处理列表出错！", e);
		}
		return result;
	}

	/**
	 * 获取我的兑换商品记录
	 *
	 * @author 朱建文 创建时间：2018年4月11日 下午2:21:22
	 */
	@ResponseBody
	@RequestMapping("/getOrderList")
	public Result<List<Map<String, Object>>> getExchangeOrderJlList(HttpServletRequest request, OPaging<Map<String, Object>> page) {
		Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
		result.setCode(-1);
		result.setMessage("获取兑换称号记录失败！");

		try {
			String token = getParamValueString(request, "token");
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
				return result;
			}

			// 每页数据条数
			int limit = getParamValueInteger(request, "limit", 50);
			page.setLimit(limit);

			// 第几页
			int offset = getParamValueInteger(request, "offset", -1);
			if (offset > 0) {
				page.setOffset((offset-1)*limit);
			}

			// 排序方式
			String order = getParamValueString(request, "order");
			if (StringUtil.isNotEmpty(order)) {
				page.setOrder(order);
			}
			page.setOrder(" DESC ");

			// 排序字段
			String sort = getParamValueString(request, "sort");
			if (StringUtil.isNotEmpty(sort)) {
				page.setSort(sort);
			}
			page.setSort(" applyTime ");

			// 兑换状态
			String state = getParamValueString(request, "state");
			if (StringUtil.isNotEmpty(state)) {
				if(state.equals("40")){
					page.getWm().put("_IN$CONVERSION_STATE","'20','30'");
				}else {
					page.getWm().put("CONVERSION_STATE", state);
				}
			}
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(userId));
			if (UserConstant.USER_ROLE_10.getId().toString().equals(pubgUser.getUserRole().toString())) {
				page.getWm().put("USER_ID", userId);
			} else if (UserConstant.USER_ROLE_20.getId().toString().equals(pubgUser.getUserRole().toString())) {
				Query query = new Query();
				query.put("_LIKE$CAPTAIN_ID", "," + userId + ",");
				PubgTeam pubgTeam = pubgTeamService.find(query);
				page.getWm().put("TEAM_ID", pubgTeam.getRowId());
				page.getWm().put("USER_ROLE", UserConstant.USER_ROLE_20.getId());
			} else if (UserConstant.USER_ROLE_30.getId().toString().equals(pubgUser.getUserRole().toString())) {
				Query query = new Query();
				query.put("_LIKE$MINISTER_ID", "," + userId + ",");
				PubgClub pubgClub = pubgClubService.find(query);
				page.getWm().put("CLUB_ID", pubgClub.getRowId());
				page.getWm().put("USER_ROLE", UserConstant.USER_ROLE_30.getId());
			}
			List<Map<String, Object>> dataList = this.pubgExchangeOrderService.getExchageOrderList(page);
			result.setCode(0);
			result.setData(dataList);
			result.setMessage("获取兑换称号记录成功！");
			log.info(result);
		} catch (Exception e) {
			log.error("前台获取兑换称号记录出错！", e);
		}
		return result;
	}

	/**
	 * 兑换商品
	 * @author 高冬冬 2018年4月12日
	 */
	@ResponseBody
	@RequestMapping("/addExchangeOrder")
	public Result<Map<String, Object>> addExchangeOrder(HttpServletRequest request, Long goodsId) {
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		result.setCode(-1);
		result.setMessage("兑换称号失败！");
		try {
			String token = getParamValueString(request, "token");
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
				return result;
			}
			if (goodsId == null) {
				result.setMessage("参数缺失【goodsId】");
				return result;
			}
			PubgUser pubgUser = pubgUserService.findByPK(Long.parseLong(userId));//当前登陆用户
			PubgExchangeGoods pubgExchangeGoods = pubgExchangeGoodsService.findByPK(goodsId);
			if (pubgExchangeGoods == null) {
				result.setMessage("称号不存在！");
				return result;
			}
			if (pubgExchangeGoods.getOpenFlag() != 1) {
				result.setMessage("称号已删除！");
				return result;
			}
			PubgExchangeOrder pubgExchangeOrder = new PubgExchangeOrder();
			pubgExchangeOrder.setUserId(pubgUser.getRowId());
			pubgExchangeOrder.setUserAccount(pubgUser.getUserAccount());
			pubgExchangeOrder.setUserRole(pubgUser.getUserRole());
			pubgExchangeOrder.setGoodsId(pubgExchangeGoods.getRowId());
			pubgExchangeOrder.setGoodsName(pubgExchangeGoods.getGoodsName());
			pubgExchangeOrder.setGoodsPrice(pubgExchangeGoods.getGoodsPrice());
			pubgExchangeOrder.setApplyTime(DateUtil.getCurrentDateTime());
			pubgExchangeOrder.setConversionState(PubgConstant.CONVERSION_STATE_10);
			
			//普通用户兑换商品 BEGIN
			if (pubgUser.getUserRole() == UserConstant.USER_ROLE_10.getId().intValue()) {
				pubgExchangeOrder.setBalance(pubgUser.getBalance());//普通用户鸡蛋数
				Long userTeamId = getLongValue(request, "userTeamId", -1l);
				Map<String,String> columns = new HashMap<String,String>();
				columns.put("ROW_ID", "rowId");
				Query query = new Query();
				query.put("USER_ID", pubgUser.getRowId());
				query.put("RELATION_STATE", PubgConstant.USER_TEAM_RELATION_STATE_2);
				List<PubgUserTeam> userTeamList = pubgUserTeamService.findList(columns,query);
				if (userTeamList == null || userTeamList.size() == 0) {
					result.setMessage("用户未加入战队，无法兑换称号！");
					return result;
				}
				if (userTeamId <= 0) {
					result.setMessage("请选择战队进行称号兑换！");
					return result;
				}
				
				query = new Query();
				query.put("TEAM_ID", userTeamId);
				query.put("USER_ID", pubgUser.getRowId());
				query.put("RELATION_STATE", PubgConstant.USER_TEAM_RELATION_STATE_2);
				PubgUserTeam pubgUserTeam = pubgUserTeamService.find(query);
				if (pubgUserTeam == null) {
					result.setMessage("查询用户战队错误！");
					return result;
				}
				
				if (pubgUserTeam.getUserTeamBalance() == null 
						|| pubgUserTeam.getUserTeamBalance() < pubgExchangeGoods.getGoodsPrice()) {
					result.setMessage("用户战队鸡蛋数不足！");
					return result;
				}
				pubgExchangeOrder.setUserTeamBalance(pubgUserTeam.getUserTeamBalance());//普通用户战队关系表鸡蛋数
				query = new Query();
				query.put("USER_ID", pubgExchangeOrder.getUserId());
				query.put("CLUB_ID", pubgUserTeam.getClubId());
				PubgUserClub pubgUserClub = pubgUserClubService.find(query);
				pubgExchangeOrder.setUserClubBalance(pubgUserClub.getUserClubBalance());//普通用户俱乐部关系表鸡蛋数
				pubgExchangeOrder.setTeamId(pubgUserTeam.getTeamId());
				pubgExchangeOrder.setTeamName(pubgUserTeam.getTeamName());
				pubgExchangeOrder.setClubId(pubgUserTeam.getClubId());
				pubgExchangeOrder.setClubName(pubgUserTeam.getClubName());
			}
			
			//战队队长兑换商品 BEGIN
			if (pubgUser.getUserRole() == UserConstant.USER_ROLE_20.getId().intValue()) {
				//查战队
				Query query = new Query();
				query.put("_LIKE$CAPTAIN_ID", "," + pubgUser.getRowId() + ",");
				PubgTeam pubgTeam = this.pubgTeamService.find(query);
				if (pubgTeam == null || pubgTeam.getTeamBalance() == null 
						|| pubgTeam.getTeamBalance() < pubgExchangeGoods.getGoodsPrice()) {
					result.setMessage("战队鸡蛋数不足！");
					return result;
				}

				pubgExchangeOrder.setTeamBalance(pubgTeam.getTeamBalance());//战队鸡蛋数
				pubgExchangeOrder.setTeamId(pubgTeam.getRowId());
				pubgExchangeOrder.setTeamName(pubgTeam.getTeamName());
				pubgExchangeOrder.setClubId(pubgTeam.getClubId());
				pubgExchangeOrder.setClubName(pubgTeam.getClubName());
			}
			
			//俱乐部部长兑换商品 BEGIN
			if (pubgUser.getUserRole() == UserConstant.USER_ROLE_30.getId().intValue()) {
				//查俱乐部
				Query query = new Query();
				query.put("_LIKE$MINISTER_ID", "," + pubgUser.getRowId() + ",");
				PubgClub pubgClub = this.pubgClubService.find(query);
				if (pubgClub == null || pubgClub.getClubBalance() == null 
						|| pubgClub.getClubBalance() < pubgExchangeGoods.getGoodsPrice()) {
					result.setMessage("俱乐部鸡蛋数不足！");
					return result;
				}

				pubgExchangeOrder.setClubBalance(pubgClub.getClubBalance());//俱乐部鸡蛋数
				pubgExchangeOrder.setClubId(pubgClub.getRowId());
				pubgExchangeOrder.setClubName(pubgClub.getClubName());
			}
			
			pubgExchangeOrderService.addExchangeOrder(pubgExchangeOrder);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("orderId", pubgExchangeOrder.getRowId());
			data.put("goodsName", pubgExchangeOrder.getGoodsName());
			data.put("conversionState", pubgExchangeOrder.getConversionState());
			result.setData(data);
			result.setCode(0);
			result.setMessage("兑换称号成功！");
		} catch (Exception e) {
			log.error("兑换称号出错了", e);
		}
		return result;
	}

	/**
	 * 修改商场物品兑换订单状态
	 * 处理完成/撤销兑换
	 *
	 * @author 高冬冬 2018年4月11日
	 */
	@ResponseBody
	@RequestMapping("/updateOrderConversionState")
	public Result<Map<String, Object>> updateOrderConversionState(HttpServletRequest request, Long orderId, String conversionState) {
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		result.setCode(-1);
		String conversionStateStr = "";
		if ("20".equals(conversionState)) {
			conversionStateStr = "同意兑换";
		} else if ("30".equals(conversionState)) {
			conversionStateStr = "撤销兑换";
		}
		result.setMessage(conversionStateStr + "失败！");
		try {
			String token = getParamValueString(request, "token");
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
				return result;
			}
			if (orderId == null) {
				result.setMessage("参数缺失【orderId】");
				return result;
			}
			if (conversionState == null) {
				result.setMessage("参数缺失【conversionState】");
				return result;
			}
			PubgUser pubgUser = pubgUserService.findByPK(Long.parseLong(userId));//当前登陆用户
			if (pubgUser == null) {
				result.setCode(-2);
				result.setMessage("请重新登陆");
				return result;
			}
			
			PubgExchangeOrder pubgExchangeOrder = pubgExchangeOrderService.findByPK(orderId);
			PubgUser orderUser = pubgUserService.findByPK(pubgExchangeOrder.getUserId());//兑换称号用户
			if (orderUser == null) {
				result.setMessage("兑换订单有误！");
				return result;
			}
			
			// 俱乐部部长不能处理普通用户兑换
			if (pubgUser.getUserRole() == UserConstant.USER_ROLE_30.getId().intValue()
					&& orderUser.getUserRole() == UserConstant.USER_ROLE_10.getId().intValue()) {
				result.setMessage("部长不能处理普通用户兑换！");
				return result;
			}
			
			if (pubgUser.getUserRole() == UserConstant.USER_ROLE_10.getId().intValue()
					|| orderUser.getUserRole() == UserConstant.USER_ROLE_30.getId().intValue()) {
				result.setMessage("您暂无权限操作！");
				return result;
			}
			
			// 查询战队所在俱乐部，获取俱乐部鸡蛋数（同意战队的申请时，需要给俱乐部加）
			PubgClub pubgClub = this.pubgClubService.findByPK(pubgExchangeOrder.getClubId());
			pubgExchangeOrder.setClubBalance(pubgClub.getClubBalance());//俱乐部鸡蛋数
			
			// 查询队员所在战队，获取战队鸡蛋数（同意队员的申请时，需要给战队加）
			PubgTeam pubgTeam = this.pubgTeamService.findByPK(pubgExchangeOrder.getTeamId());
			pubgExchangeOrder.setTeamBalance(pubgTeam.getTeamBalance());//战队鸡蛋数
			
			// 队员所在战队鸡蛋数
			if (UserConstant.USER_ROLE_10.getId().equals(orderUser.getUserRole())) {
				
				Query query = new Query();
				query.put("USER_ID", orderUser.getRowId());
				query.put("TEAM_ID", pubgTeam.getRowId());
				query.put("RELATION_STATE", PubgConstant.USER_TEAM_RELATION_STATE_2);
				PubgUserTeam pubgUserTeam = this.pubgUserTeamService.find(query);
				pubgExchangeOrder.setBalance(pubgUserTeam.getUserTeamBalance());
			}
			
			pubgExchangeOrderService.updateOrderConversionState(pubgExchangeOrder, conversionState, pubgUser.getRowId(), pubgUser.getUserAccount(), "");
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("orderId", pubgExchangeOrder.getRowId());
			data.put("goodsName", pubgExchangeOrder.getGoodsName());
			data.put("conversionState", conversionState);
			result.setData(data);
			result.setCode(0);
			result.setMessage(conversionStateStr + "成功！");
		} catch (Exception e) {
			log.error("修改商场物品兑换订单状态出错了", e);
		}
		return result;
	}

}
